<template>
  <div id="wrapper">
    <el-steps style="padding:10px;" :active="active">
      <el-step title="准备"></el-step>
      <el-step title="开PING"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <!-- 节点配置 -->
    <el-card v-if="this.active === 1" style="padding:10px;" class="box-card">
      <div slot="header" class="clearfix">
        <span>
          <i class="el-icon-edit-outline"></i>准备测试数据
        </span>
      </div>
      <!-- 操作按钮 -->
      <div class="clearfix">
        <el-button-group style="float:right;">
          <el-button size="mini" @click="nodeImportClickHandler">导 入</el-button>
          <el-button size="mini" @click="nodeExportClickHandler">导 出</el-button>
          <el-button type="primary" @click="newVisible = true" size="mini">新增</el-button>
        </el-button-group>
      </div>
      <!-- 新增节点弹窗 -->
      <el-dialog
        title="新增PING点"
        :modal="false"
        :visible.sync="newVisible"
        width="60%"
        :before-close="handleNewClose"
      >
        <!-- 测试配置信息列表 -->
        <el-form :model="pingInfo" style="padding:20px 0;" label-width="80px">
          <el-form-item label="名称">
            <el-input v-model="pingInfo.name" placeholder="输入测试名称"></el-input>
          </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="pingInfo.ip" placeholder="输入请求地址"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeNewNode">取 消</el-button>
          <el-button type="primary" @click="onClickNewNodeHandler">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 节点列表-->
      <el-table size="mini" height="300" :data="nodeData" stripe style="width: 100%;padding:5px 0;">
        <el-table-column sortable prop="name" label="名称"></el-table-column>
        <el-table-column sortable prop="ip" label="地址"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="editNode(scope.row)" type="text" size="small">编辑</el-button>
            <el-popconfirm @onConfirm="deleteNode(scope.row)" title="确认删除该节点吗？">
              <el-button
                style="color:#f00;margin-left:10px;"
                type="text"
                size="small"
                slot="reference"
              >删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        type="success"
        @click="onStartClickHandler"
        style="width:100%;margin-top:30px;"
      >开始测PING</el-button>
    </el-card>
    <el-card v-if="this.active === 2" style="padding:10px;" class="box-card">
      <div slot="header" class="clearfix">
        <span>
          <i class="el-icon-loading"></i>
          当前测速节点({{ nowStatus.index }}/{{ nodeData.length }})
        </span>
        <el-link
          @click="stopAllClickHandler"
          type="primary"
          style="float: right; padding: 3px 0;width:80px;"
          :disabled="!isCanStopAll"
        >终止PING</el-link>
      </div>
      <div style="padding:3px;">
        <el-row style="padding:8px;">
          <el-col :span="12">名称：{{ nowStatus.name }}</el-col>
          <el-col :span="12">地址：{{ nowStatus.ip }}</el-col>
        </el-row>
      </div>
    </el-card>
    <el-button
      v-if="this.active === 3"
      style="width:100%;margin:20px 0;"
      type="primary"
      @click="reStart"
    >
      <i class="el-icon-refresh"></i>重新开始
    </el-button>
    <div class="clearfix" style="padding:30px;">
      <span style="font-size:20px;font-weight:bold;">测速结果</span>
      <el-link
        type="primary"
        style="float: right; margin: 3px 10px"
        @click="exportAllDataHandler"
      >导出</el-link>
      <el-link type="danger" style="float: right; margin: 3px 10px" @click="clearAllHandler">清空</el-link>
    </div>
    <el-table size="mini" :data="tableData" stripe style="width: 100%;padding:5px 30px;">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" class="demo-table-expand">
            <el-form-item label="第一次测试">
              <span>{{ props.row.test1 ? props.row.test1 :'-' }}</span>
            </el-form-item>
            <el-form-item label="第二次测试">
              <span>{{ props.row.test2 ? props.row.test2 :'-'}}</span>
            </el-form-item>
            <el-form-item label="第三次测试">
              <span>{{ props.row.test3 ? props.row.test3 :'-'}}</span>
            </el-form-item>
            <el-form-item label="第四次测试">
              <span>{{ props.row.test4 ? props.row.test4 :'-'}}</span>
            </el-form-item>
            <el-form-item label="结果">
              <span>{{ props.row.result }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column sortable prop="name" label="名称"></el-table-column>
      <el-table-column sortable prop="ip" label="地址"></el-table-column>
      <el-table-column sortable prop="result" label="PING RESULT"></el-table-column>
    </el-table>
  </div>
</template>

<script>
const { dialog } = require("electron").remote;
import { ipcRenderer } from "electron";
import { DataImport, DataExport, CsvExport } from "../../util/FileIO";
export default {
  name: "ping-test",
  data () {
    return {
      active: 1,
      newVisible: false,
      pingInfo: {
        id: "",
        name: "",
        ip: ""
      },
      nowStatus: {
        index: "-",
        ip: "-",
        name: "-"
      },
      tableData: [],
      nodeData: [],
      isCanStopAll: true
    };
  },
  mounted () {
    ipcRenderer.on("setInitvalue", (event, { index, name, ip }) => {
      this.nowStatus.ip = ip;
      this.nowStatus.name = name;
      this.nowStatus.index = index;
    });
    ipcRenderer.on("pushResult", (event, info) => {
      this.pushResult(info);
    });
    ipcRenderer.on("onTestOver", (event, info) => {
      this.onTestOver();
    });
    ipcRenderer.on("onSkipOrStop", (event, info) => {
      this.isCanStopAll = true;
    });
  },
  methods: {
    reStart () {
      this.$confirm("您确定要重新开始吗，请确认您的测速结果已经保存?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          Object.assign(this.pingInfo, {
            id: "",
            name: "",
            ip: ""
          });
          Object.assign(this.nowStatus, {
            name: "-",
            ip: "-",
            index: "-"
          });
          this.tableData.splice(0, this.tableData.length);
          this.nodeData.splice(0, this.nodeData.length);
          this.isCanStopAll = true;
          this.active = 1;
        })
        .catch(() => { });
    },
    stopAllClickHandler () {
      this.$confirm("您确定要终止运行吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.isCanStopAll = false;
          ipcRenderer.send("stopPingAll");
        })
        .catch(() => { });
    },
    pushResult (res) {
      this.tableData.push({
        ...res
      });
    },
    deleteNode (pingInfo) {
      for (let i = 0; i < this.nodeData.length; i++) {
        if (this.nodeData[i].id === pingInfo.id) {
          this.nodeData.splice(i, 1);
          break;
        }
      }
    },
    editNode (pingInfo) {
      Object.assign(this.pingInfo, pingInfo);
      this.newVisible = true;
    },
    closeNewNode () {
      this.newVisible = false;
      this.pingInfo.id = "";
      this.pingInfo.name = "";
      this.pingInfo.ip = "";
    },
    onClickNewNodeHandler () {
      if (!this.pingInfo.id) {
        this.pingInfo.id = new Date().valueOf() + "";
        this.nodeData.push({ ...this.pingInfo });
      } else {
        for (let i = 0; i < this.nodeData.length; i++) {
          if (this.nodeData[i].id === this.pingInfo.id) {
            Object.assign(this.nodeData[i], this.pingInfo);
            break;
          }
        }
      }
      this.closeNewNode();
    },
    nodeImportClickHandler () {
      dialog.showOpenDialog(
        {
          title: "导入PING配置",
          //过滤条件
          filters: [{ name: "PING数据", extensions: ["pingconf"] }]
        },
        res => {
          DataImport(res[0], data => {
            if (!data) this.$message.error("导入失败，请检查文件格式。");
            else {
              this.nodeData.splice(0, this.nodeData.length);
              this.nodeData.push(...data);
            }
          });
        }
      );
    },
    nodeExportClickHandler () {
      dialog.showSaveDialog(
        {
          title: "导出PING配置",
          //过滤条件
          filters: [{ name: "PING数据", extensions: ["pingconf"] }]
        },
        res => {
          DataExport(res, this.nodeData, err => {
            if (err) this.$message.error("导出失败:" + err);
            else this.$message({ message: "导出成功", type: "success" });
          });
        }
      );
    },
    onStartClickHandler () {
      if (this.nodeData.length <= 0) {
        this.$message.error("请配置PING节点");
        return;
      }
      this.active = 2;
      this.startTest();
    },
    handleNewClose () {
      this.newVisible = false;
    },
    startTest () {
      ipcRenderer.send("pingTestStart", this.nodeData);
    },
    clearAllHandler () {
      this.$confirm("您确定要清空结果吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.tableData.splice(0, this.tableData.length);
        })
        .catch(() => { });
    },
    exportAllDataHandler () {
      dialog.showSaveDialog(
        {
          title: "导出结果集",
          //过滤条件
          filters: [{ name: "Excel数据表", extensions: ["csv"] }]
        },
        res => {
          CsvExport(
            res,
            "名称,地址,第一轮,第二轮,第三轮,第四轮,结果",
            ["name", "ip", "test1", "test2", "test3", "test4", "result"],
            this.tableData,
            err => {
              if (err) this.$message.error("导出失败:" + err);
              else this.$message({ message: "导出成功", type: "success" });
            }
          );
        }
      );
    },
    onTestOver () {
      this.active = 3;
    }
  }
};
</script>

<style>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 100%;
}
</style>
